package com.example.activitysys.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.activitysys.entity.ClaimRecord;
import com.example.activitysys.entity.LostItem;
import com.example.activitysys.mapper.ClaimRecordMapper;
import com.example.activitysys.mapper.LostItemMapper;
import com.example.activitysys.service.ClaimRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class ClaimRecordServiceImpl extends ServiceImpl<ClaimRecordMapper, ClaimRecord> implements ClaimRecordService {

    @Autowired
    private LostItemMapper lostItemMapper;

    /**
     * 认领物品（事务 + 乐观锁）
     * @param itemId 物品ID
     * @param claimer 认领人
     * @param contact 联系方式
     * @return 认领是否成功
     */
    @Override
    @Transactional
    public boolean claimItem(Long itemId, String claimer, String contact) {
        // 1. 查询物品（带 version）
        LostItem item = lostItemMapper.selectById(itemId);
        if (item == null || item.getStatus() == 1) {
            throw new RuntimeException("物品已被认领或不存在");
        }

        // 2. 更新物品状态（乐观锁）
        int updated = lostItemMapper.update(null,
                new UpdateWrapper<LostItem>()
                        .set("status", 1)
                        .eq("id", itemId)
                        .eq("version", item.getVersion()) // 乐观锁条件
        );

        if (updated == 0) {
            throw new RuntimeException("并发冲突：物品已被他人认领");
        }

        // 3. 插入认领记录
        ClaimRecord record = new ClaimRecord();
        record.setItemId(itemId);
        record.setClaimer(claimer);
        record.setContact(contact);
        record.setClaimTime(LocalDateTime.now());
        this.save(record);

        return true;
    }
}